package edu.ufl.cise.sanitas.client;

import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;

public class DailyLog extends Activity {

	private static final int FINISHEDIT_ID = Menu.FIRST;
	private static final int DIALOG_DATE_PICKER_ID = 0;
	private int mDay;
	private int mMonth;
	private int mYear;
	
	private DatePickerDialog.OnDateSetListener mDateSetListener =
        new DatePickerDialog.OnDateSetListener() {

            public void onDateSet(DatePicker view, int year, 
                                  int monthOfYear, int dayOfMonth) {
                mYear = year;
                mMonth = monthOfYear;
                mDay = dayOfMonth;
                updateDisplay();
            }
        };
	private TextView mDateDisplay;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dailylog);
		
		mDateDisplay = (TextView) findViewById(R.id.dailylog_text_date);
		
		Button changeDateButton = (Button) findViewById(R.id.dailylog_btn_changedate);
		
		changeDateButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showDialog(DIALOG_DATE_PICKER_ID);
			}
			
		});
		
		final Calendar c = Calendar.getInstance();
		mYear = c.get(Calendar.YEAR);
		mMonth = c.get(Calendar.MONTH);
		mDay = c.get(Calendar.DAY_OF_MONTH);
		updateDisplay();
		
		// TODO: Add edit buttons and listeners
	}

	private void updateDisplay() {
        mDateDisplay.setText(
                new StringBuilder()
                        .append(mMonth + 1).append("-")
                        .append(mDay).append("-")
                        .append(mYear).append(" "));
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_DATE_PICKER_ID:
			return new DatePickerDialog(this,
                    mDateSetListener,
                    mYear, mMonth, mDay);
		}
		return super.onCreateDialog(id);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, FINISHEDIT_ID, 0, R.string.dailylog_menu_finishedit);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case FINISHEDIT_ID:
			// TODO: put extra bundle
			
			Intent i = new Intent();
			setResult(RESULT_OK, i);
			finish();
			
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

}
